// packageQuestionnaire/pages/list/list.js
import Questionnaire from "../../../service/Questionnaire";
import {getStorageSync} from "../../../utils/Storage";
import Toast from "@vant/weapp/toast/toast";
let TimeOut = null;
Page({

    /**
     * 页面的初始数据
     */
    data: {
        isLoading: true, //页面加载动画
        list: [],
        current: 0,
        btn: {
            text: "已完成（0）", //已做题
            isDisabled: true, //是否禁用
            isLoading: false //是否展示加载动画
        }
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        this._userInfo = getStorageSync("userInfo") || {};
        this.data._options = options;
        this.getList();
    },

    /*
    * 获取调查问卷列表
    * 根据type 不同获取不同列表信息
    * */
    getList: async function () {
        try {
            let type = this._userInfo.type || getStorageSync("userType");
            let res = type === 1 ? await Questionnaire.getPerson() : await Questionnaire.getOrg();
            this.setData({list: res})
        } catch (e) {
            console.error(e)
        } finally {
            this.setData({isLoading: false})
        }
    },

    /*
    * swiper切换
    * */
    onSwiperChange: function (e) {
        this.setData({current: e.detail.current})
    },

    /*
    * 选择单选框
    * */
    onRadioSelected(e) {
        const that = this;
        let index = e.currentTarget.dataset.index;
        let list = this.data.list;
        let value = e.detail;
        if (list[index].radio !== value) {
            this.setData({
                ["list[" + index + "].radio"]: value
            });
            clearTimeout(TimeOut);
            TimeOut = setTimeout(function () {
                if (index < list.length - 1) {
                    that.setData({current: index + 1})
                }
            }, 500)
            that._checked();
        }
    },

    /*
    * 验证
    * */
    _checked: function () {
        let list = this.data.list;
        let filter = list.filter(function (item) {
            return !!item.radio
        })
        let num = filter.length;
        if (num > 0) {
            this.setData({"btn.text": "已完成（" + filter.length + "）"});
            if (num === list.length) {
                this.setData({
                    "btn.isDisabled": false,
                    "btn.text": "确认提交"
                })
            }
        }
    },

    /*
    * 提交数据
    * */
    onSubmit: async function () {
        try {
            Toast.loading({
                mask: true,
                duration: 0, // 持续展示 toast
                message: "提交中..."
            });
            let userInfo = this._userInfo;
            let options = this.data._options;
            let type = userInfo.type || getStorageSync("userType");
            let list = this.data.list;
            let answer = list.map(function (item) {
                return item.radio
            })
            this.setData({"btn.isLoading": true});
            type === 1 ? await Questionnaire.savePerson({answer}) : await Questionnaire.saveOrg({answer});
            Toast.clear();
            setTimeout(function () {
                wx.redirectTo({url: "/packageQuestionnaire/pages/result/result?from=" + options.from})
            }, 300)
        } catch (e) {
            Toast.fail({message: e.errMsg});
            console.error(e)
        } finally {
            this.setData({"btn.isLoading": false});
        }
    }
})